package Server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JOptionPane;

import Util.XMLUtil;

public class ServerConnection extends Thread {
	private Server server;
	private ServerSocket serverSocket;
	private Socket socket;
	public ServerConnection(Server server,int port){
		this.server = server;
		try{
			this.serverSocket = new ServerSocket(port);
			server.getCurState().setText("运行");
			server.getStart().setEnabled(false);
		}catch(IOException e){
			e.printStackTrace();
			JOptionPane.showMessageDialog(this.server, "端口被占用","错误",JOptionPane.ERROR_MESSAGE);
		}
	}
	private boolean isUserExist(String userName){
		if (this.server.getUsers().containsKey(userName)){
			return true;
		}else{
			return false;
		}
	}
	public void run(){
		while (true){
			try{
				this.socket = serverSocket.accept();
				InputStream is = socket.getInputStream();
				OutputStream os = socket.getOutputStream();
				byte[] buf = new byte[5000];
				int length = is.read(buf);
				String loginXML = new String(buf,0,length);
				String userName = XMLUtil.extractUsername(loginXML);
				//判断是否已被登录
				if(this.isUserExist(userName)){
					os.write(XMLUtil.constructResponse("fail").getBytes());
				}else{
					os.write(XMLUtil.constructResponse("success").getBytes());
					DeallingMessage deallingMessage = new DeallingMessage(this.server,socket);
					this.server.getUsers().put(userName, deallingMessage);
					deallingMessage.updateUserList();
					deallingMessage.start();
				}
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}
}
